package cn.hxzy.service.impl;

import cn.hxzy.domain.School;
import cn.hxzy.domain.User;
import cn.hxzy.domain.UserClass;
import cn.hxzy.mapper.UserMapper;
import cn.hxzy.service.UserService;
import cn.hxzy.util.JwtUtils;
import cn.hxzy.util.MsmUtil;
import cn.hxzy.util.ThreadLocalUtil;
import com.aliyun.oss.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * 项目名: education-platform
 * 当前用户: 18735
 * 创建日期: 2024/6/22 下午2:46
 * 项目介绍:
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static final Integer CODE_LENGTH = 6;

    /**
     * 登录
     * @param userName 账号
     * @param userPass 密碼
     * @return jwt
     */
    @Override
    public String login(String userName, String userPass) {

        Long userId = userMapper.login(userName, userPass);

        if (userId==0){
            return null;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString;
        User user = userMapper.selectById(userId);
        ThreadLocalUtil.setUser(user);
        try {
            jsonString = objectMapper.writeValueAsString(user);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        String token = JwtUtils.createJWT(jsonString);
        if (StringUtils.isNullOrEmpty(token)){
            return null;
        }
        redisTemplate.opsForValue().set(userId.toString(),token,60*60*2);
        return token;
    }

    /**
     * 修改用户信息
     * @param user 用戶信息
     * @return 1 修改成功
     */
    @Override
    public Boolean updateUser(User user) {
        return userMapper.updateById(user)>0;
    }



    /**
     * 根据id查询用户信息
     * @return 用户信息
     */
    @Override
    public User selectById() {
//        User user = ThreadLocalUtil.getUser();
//        if (ObjectUtils.isEmpty(user)){
//            return null;
//        }
        return userMapper.selectById(2L);
    }

    /**
     * 修改密码前置，根据密码查询用户信息
     * @param userPass 密码
     * @return 当前密码
     */
    @Override
    public Integer selectOldPwd(String userPass) {
        User user = ThreadLocalUtil.getUser();
        String newPass = userMapper.selectOldPwd(user.getUserId(), userPass);
        if (userPass.equals(newPass)){
            return 1;
        }
        return 0;
    }

    /**
     * 修改密碼
     * @param userPass 密碼
     * @return 影响行数
     */
    @Override
    public int updatePwd(String userPass) {
        ThreadLocalUtil.getUser();
        User user = new User();
        Long userId = ThreadLocalUtil.getUser().getUserId();
        if (ObjectUtils.isEmpty(userId)){
            return 0;
        }
        user.setUserId(userId);
        user.setUserPass(userPass);
        int i = userMapper.updateById(user);
        if (i>0){
            return 1;
        }
        return -1;
    }



    /**
     * 新增学校
     * @param school
     * @return 1 新增成功
     */
    @Override
    public int save(School school) {
        return 0;
    }

    /**
     * 获取验证码
     * @param userPhone 手机号
     * @return 验证码
     */
    @Override
    public String getCode(String userPhone) {
        String code = "";
        //首先从redis中获取
        code = redisTemplate.opsForValue().get(userPhone);
        if (!StringUtils.isNullOrEmpty(code)){
            return code;
        }
        Random random = new Random();
        //生成验证码,传递阿里云进行发送
        for (int i = 0; i < CODE_LENGTH; i++) {
            code += random.nextInt(10);
        }
        Map<String,String> param = new HashMap<>();
        param.put("code",code);
        if (MsmUtil.send(param,userPhone)){
            redisTemplate.opsForValue().set(userPhone,code,60);
            return code;
        }
        log.error("Failed to send SMS code to phone number: " + userPhone); // 记录发送失败日
        return null;
    }

    /**
     * 手机号登录
     * @param userPhone 手机号
     * @param code 验证码
     * @return jwt
     */
    @Override
    public String loginByCode(String userPhone, String code) {

        if (code.equals(redisTemplate.opsForValue().get(userPhone))){

            Long userId = userMapper.loginByCode(userPhone);

            if (userId==0){
                return null;
            }

            //根据用户编号获取用户信息存入线程
            String token = JwtUtils.createJWT(userId.toString());
            if (StringUtils.isNullOrEmpty(token)){
                return null;
            }
            User user = userMapper.selectById(userId);
            ThreadLocalUtil.setUser(user);
            redisTemplate.opsForValue().set(userId.toString(),token,60*60*2);
            return token;

        }
        return null;
    }

    /**
     * 根据编号查询班级信息
     * @return 返回用户所对应的所有班级信息
     */
    @Override
    public List<UserClass> selectClassById() {
        User user = ThreadLocalUtil.getUser();
        List<UserClass> userClassList = userMapper.selectClassById(user.getUserId());
        if (ObjectUtils.isEmpty(userClassList)){
            return null;
        }
        return userClassList;
    }


}
